package com.sskj.level.ui.fragment;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.CoinType;
import com.sskj.level.bean.TradeInfoBean;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.LevelFragmentPresenter;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.MoreLessBean;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.sskj.level.http.HttpConfig.DEFAULT_COIN;

@Route(path = RConfig.LEVEL_FRAGMENT_MAIN)//杠杆（合约）交易主页面
public class LevelFragment extends BaseFragment<LevelFragmentPresenter> {
    @Inject
    UserViewModel userViewModel;
    @BindView(R2.id.ivTopLeft)
    ImageView ivTopLeft;
    @BindView(R2.id.tvTitle)
    TextView tvTitle;
    @BindView(R2.id.ivTopRight)
    ImageView ivTopRight;
    @BindView(R2.id.priceNow)
    TextView priceNow;
    @BindView(R2.id.llTop)
    LinearLayout llTop;
    @BindView(R2.id.changeRate)
    TextView changeRate;
    @BindView(R2.id.tvRMB)
    TextView tvRMB;
    @BindView(R2.id.highText)
    TextView highText;
    @BindView(R2.id.highPrice)
    TextView highPrice;
    @BindView(R2.id.lowText)
    TextView lowText;
    @BindView(R2.id.lowPrice)
    TextView lowPrice;
    @BindView(R2.id.tvBao)
    TextView tvBao;
    @BindView(R2.id.market_info)
    LinearLayout marketInfo;

    @BindView(R2.id.level_zx)
    LinearLayout levelZX;
    @BindView(R2.id.level_k_line)
    LinearLayout levelKLine;

    @BindView(R2.id.tradeFrameLayout)
    FrameLayout tradeFrameLayout;
    @BindView(R2.id.tvHolderTrade)
    TextView tvHolderTrade;
    @BindView(R2.id.tvAllTrade)
    TextView tvAllTrade;
    @BindView(R2.id.ivAllTrade)
    ImageView ivAllTrade;
    @BindView(R2.id.holderFrameLayout)
    FrameLayout holderFrameLayout;
    @BindView(R2.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;

    String code = DEFAULT_COIN;
    private UserData userData;
    private Disposable subscribe;

    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_main;
    }

    @Override
    public LevelFragmentPresenter getPresenter() {
        return new LevelFragmentPresenter();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        RxBus.getDefault().register(this);
        tvTitle.setText(code);
        mPresenter.getProduct(code);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                tvAllTrade.setVisibility(View.VISIBLE);
                ivAllTrade.setVisibility(View.VISIBLE);
            } else {
                userData = null;
                tvAllTrade.setVisibility(View.GONE);
                ivAllTrade.setVisibility(View.GONE);
            }
        });
        ClickUtil.click(ivTopLeft, () -> {
            ARouter.getInstance().build(RConfig.LEVEL_SLIDE).navigation();
        });
        ClickUtil.click(levelKLine, () -> {
            ARouter.getInstance().build(RConfig.APP_MARKET_NEW).withString(Constans.CODE, code).navigation();
        });
        ClickUtil.click(levelZX, () -> {
            ARouter.getInstance().build(RConfig.APP_SELF_CHOOSE).navigation();
        });
        ClickUtil.click(tvAllTrade, () -> {
            ARouter.getInstance().build(RConfig.LEVEL_TRADE)
                    .withString("code", code)
                    .navigation();
        });
        smartRefreshLayout.setRefreshHeader(new MaterialHeader(getActivity()));
        Fragment buyAndSellFragment = (Fragment) ARouter.getInstance().build(RConfig.LEVEL_FRAGMENT_BUY_AND_SELL)
                .navigation();
        Fragment holderFragment = (Fragment) ARouter.getInstance().build(RConfig.LEVEL_FRAGMENT_CURRENT_HOLDER).withString(Constans.CODE, code).navigation();
        FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.tradeFrameLayout, buyAndSellFragment);
        fragmentTransaction.add(R.id.holderFrameLayout, holderFragment);
        fragmentTransaction.show(buyAndSellFragment);
        fragmentTransaction.show(holderFragment);
        fragmentTransaction.commitNow();

        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            RxBus.getDefault().send(RxBusCode.LEVEL_FRESH);
            smartRefreshLayout.finishRefresh(3);
        });
//        startTimer();

    }

    private void startTimer() {
        DisposUtil.close(subscribe);
        subscribe = Flowable.interval(0, 5, TimeUnit.SECONDS)
                .onBackpressureDrop()
                .subscribe(i -> mPresenter.getRisk());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(CoinType coinType) {
        code = coinType.getCode();
        tvTitle.setText(code);
        mPresenter.getProduct(code);
    }

    /**
     * K线图选择做多做空
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void chooseLevel(MoreLessBean moreLessBean) {
        code = moreLessBean.getCode();
        tvTitle.setText(code);
        mPresenter.getProduct(code);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(StockCoinBean.StockProductVOBean stock) {
        if (stock.getCode().equals(code) && getActivity() != null) {
            if (tvRMB != null) {
                tvRMB.setText("≈" + stock.getCnyPrice() + "CNY");

                if (!TextUtils.isEmpty(stock.getPrice())) {
                    priceNow.setText(stock.getPrice());

                    tvRMB.setText("≈" + stock.getCnyPrice() + "CNY");
                }
                if (Double.valueOf(stock.getChange()) > 0) {
                    changeRate.setTextColor(ContextCompat.getColor(getActivity(), R.color.levelGreenText));
                    priceNow.setTextColor(ContextCompat.getColor(getActivity(), R.color.levelGreenText));

                } else {
                    changeRate.setTextColor(ContextCompat.getColor(getActivity(), R.color.levelRedText));
                    priceNow.setTextColor(ContextCompat.getColor(getActivity(), R.color.levelRedText));

                }
                changeRate.setText(stock.getChangeRate());
                highPrice.setText(stock.getHigh());
                lowPrice.setText(stock.getLow());
                priceNow.setText(stock.getPrice());
            }
        }
    }

    public void updateRisk(TradeInfoBean data) {
        if (tvBao != null) {
            try {
                AndroidSchedulers.mainThread().scheduleDirect(() -> {
                    if (tvBao == null) {
                        return;
                    }
                    if (data != null) {
                        tvBao.setText(String.format(App.INSTANCE.getString(R.string.levelLevelFragment5), data.getProportion()));
                    } else {
                        tvBao.setText(String.format(App.INSTANCE.getString(R.string.levelLevelFragment5), "--"));
                    }
                });
            } catch (Exception e) {

            }
        }
    }


}
